package main

func main() {

}

type ListNode struct {
	Next *ListNode
	Val  int
}

func reverseKGroup(head *ListNode, k int) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	head = &ListNode{
		Next: head,
	}
	prev := head
	start := head.Next
	var end *ListNode
	var pNext *ListNode
	for start != nil {
		end = start
		for i := 1; i < k; i++ {
			if end.Next != nil {
				end = end.Next
			} else {
				return head.Next
			}
		}
		pNext = end.Next
		end.Next = nil
		prev.Next = reverse(start)
		start.Next = pNext
		prev = start
		start = pNext
	}
	return head.Next
}

func reverse(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	var pre *ListNode
	var next *ListNode
	for head != nil {
		next = head.Next // 存储当前头节点的下一个节点
		head.Next = pre  // 当前头节点指向前驱节点
		pre = head       // 再以当前头节点为前驱
		head = next      //存储的下一节点为下一次的头节点
	}
	return pre //返回最后操作的头节点
}
